<?php

namespace app\api\logic;


use app\api\cache\KeysUtil;
use app\api\cache\MemberCache;
use app\api\cache\RedisCache;
use app\api\consDir\ErrorConst;
use app\api\services\CardService;
use app\api\services\MemberService;
use app\api\services\PayService;
use app\api\services\RabbitMqService;
use app\api\services\ServiceCenterService;
use app\common\libs\Singleton;
use app\common\models\Card\Card;
use app\common\models\Card\CardOrder;
use app\common\models\Card\CardUser;
use app\common\models\Card\CardUserItem;
use app\common\models\Card\CardUserItemLog;
use app\common\models\Order\ServiceOrder;
use app\common\models\Service\Service;
use app\common\models\Service\ServiceAmountLog;
use app\common\models\Service\Services;
use app\common\models\Service\ServicesCate;
use app\common\models\Service\ServicesOrder;
use app\common\models\Service\ServicesOrderItemLog;
use app\common\models\Service\ServicesUser;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

/**
 * 订单模块
 * Class MemberLogic
 * @package app\api\logic
 */
class LoftLogic extends BaseLogic
{
    use Singleton;


    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function loftList($page,$pageSize): array
    {
        $where = [
            ['user_id','=',$this->userinfo->id]
        ];

        $list = Service::getInstance()->where($where)->order('id desc')->page($page,$pageSize)->select();
        return !empty($list) ? $list->toArray() : [];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function servicesList($page, $pageSize, $cateId, $serviceId): array
    {
        $where = [
            ['deleted','=',0],
            ['status','=',1]
        ];
        if($cateId){
            $where[] = ['cate_id','=',$cateId];
        }
        $list = Services::getInstance()->where($where)->order('id desc')->page($page,$pageSize)->select();
        foreach ($list as &$v){
            $where = [
                ['user_id','=',$this->userinfo->id],
                ['services_id','=',$v['id']],
                ['service_id','=',$serviceId]
            ];
            $v['selected'] = ServicesUser::getInstance()->where($where)->count() > 0 ? 1 : 0;
        }
        return !empty($list) ? $list->toArray() : [];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function servicesCate(): array
    {
        $where = [
            ['deleted','=',0]
        ];
        $list = ServicesCate::getInstance()->where($where)->order('sort desc,id desc')->select();
        return !empty($list) ? $list->toArray() : [];
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function servicesUserAdd($ids, $status, $serviceId): bool
    {
        if(empty($ids)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, 'ids不能为空');
        }
        if(!in_array($status,[1,2])){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '状态错误');
        }
        $where = [
            ['id','in',$ids],
            ['deleted','=',0]
        ];
        $list = Services::getInstance()->where($where)->select();
        foreach($list as $k=>$v){
            $map = [
                ['services_id','=',$v['id']],
                ['service_id','=',$serviceId]
            ];
            $servicesUser = ServicesUser::getInstance()->where($map)->find();
            if(!empty($servicesUser)){
                $servicesUser->up_down_status = $status;
                $servicesUser->service_id = $serviceId;
                $servicesUser->update_at = date('Y-m-d H:i:s');
                $servicesUser->save();
            }else{
                $data = [
                    'services_id' => $v['id'],
                    'user_id' => $this->userinfo->id,
                    'up_down_status' => 1,
                    'title' => $v['title'],
                    'market_price' => $v['market_price'],
                    'sell_price' => $v['sell_price'],
                    'cost_price' => $v['cost_price'],
                    'cover_img' => $v['cover_img'],
                    'cate_id' => $v['cate_id'],
                    'content' => $v['content'],
                    'remark' => $v['remark'],
                    'rate' => $v['rate'],
                    'status' => $v['status'],
                    'service_id' => $serviceId,
                    'is_order' => $v['is_order'],
                    'order_phone' => $v['order_phone'],
                    'can_start_time' => $v['can_start_time'],
                    'can_end_time' => $v['can_end_time'],
                    'items' => $v['items'],
                    'count' => $v['count'],
                    'expire_at' => $v['expire_at'],
                ];
                ServicesUser::getInstance()->insert($data);
            }
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function serviceOrderList($page, $pageSize, $serviceId,$status,$orderNo): array
    {
        $where = [
            ['deleted','=',0],
            ['service_id','=',$serviceId]
        ];
        if(is_numeric($status)){
            $where[] = ['status','=',$status];
        }
        if(!empty($orderNo)){
            $where[] = ['order_no','=',$orderNo];
        }
        $list = ServiceOrder::getInstance()->where($where)->order('id desc')->page($page,$pageSize)->select();
        foreach($list as &$v){
            $service = Service::getInstance()->where('id',$v['serviceId'])->find();
            $v['serviceName'] = $service['name'] ?? '';
            if($v['type'] == 1){
                $v['coverImg'] = $service['coverImg'] ?? '';
            }
        }
        return ['rows' => !empty($list) ? $list->toArray() : []];
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function servicesUserList($page, $pageSize, $serviceId, $status): array
    {
        if(empty($serviceId)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, 'serviceId不能为空');
        }
        $where = [
            ['deleted','=',0],
            ['service_id','=',$serviceId]
        ];
        if(is_numeric($status)){
            $where[] = ['up_down_status','=',$status];
        }
        $list = ServicesUser::getInstance()->where($where)->order('id desc')->page($page,$pageSize)->select();
        return ['rows' => !empty($list) ? $list->toArray() : []];
    }

    public function servicesUserStatus($ids,$status): bool
    {
        if(empty($ids)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, 'ids不能为空');
        }
        $data = [
            'up_down_status' => $status,
            'update_at' => date('Y-m-d H:i:s')
        ];
        ServicesUser::getInstance()->where('id','in',$ids)->update($data);
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function check($orderNo,$serviceId): bool
    {
        if(empty($orderNo)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '订单号不能为空');
        }
        $order = ServiceOrder::getInstance()->where('order_no',$orderNo)->find();
        if(empty($order)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '订单不存在');
        }
        $where = [
            ['id','=',$serviceId],
            ['deleted','=',0]
        ];
        $service = Service::getInstance()->where($where)->find();
        if(empty($service)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '不是生活馆身份');
        }
        if($order['count'] <= 0){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '核销次数已用完');
        }
        $price = bcadd($order['pay_price'],$order['deduction'],2);
        $money = $order['count'] > 0 ? bcdiv($price,$order['count'],2) : $price;
        ServiceOrder::getInstance()->startTrans();
        try{
            $order->update_at = date('Y-m-d H:i:s');
            $order->check_time = date('Y-m-d H:i:s');
            $order->used_count++;
            if($order->count > 0){
                if($order->count == $order->used_count){
                    $order->status = 2;
                }
            }else{
                $order->status = 2;
            }

            $order->save();

            ServiceCenterService::getInstance()->dividend($order);

            //核销记录
            $data = [
                'user_id' => $order['user_id'],
                'order_no' => $orderNo,
                'title' => $order['title'],
                'check_user_id' => $this->userinfo->id,
                'image' => $order['cover_img'],
                'service_province' => $service['service_province'],
                'service_province_id' => $service['service_province_id'],
                'service_city' => $service['service_city'],
                'service_city_id' => $service['service_city_id'],
                'service_country' => $service['service_country'],
                'service_country_id' => $service['service_country_id'],
                'service_street' => $service['service_street'],
                'service_street_id' => $service['service_street_id'],
                'service_comm' => $service['service_comm'],
                'service_comm_id' => $service['service_comm_id'],
                'detail_address' => $service['detail_address'],
                'price' => $money,
            ];
            ServicesOrderItemLog::getInstance()->insert($data);
        }catch (\Exception $e){
            ServiceOrder::getInstance()->rollback();
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, $e->getMessage().$e->getLine());
        }
        ServiceOrder::getInstance()->commit();
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function info($serviceId): array
    {
        if(empty($serviceId)){
            CommonUtil::throwException(ErrorConst::PARAM_ERROR, '订单号不能为空');
        }
        $service = Service::getInstance()->where('id',$serviceId)->find();
        return !empty($service) ? $service->toArray() : [];
    }

    public function getServiceAmountLog($startAt, $endAt, $logType, $page, $pageSize, $serviceId): array
    {
        $where = [
            ['user_id', '=', $this->userinfo->id],
            ['service_id','=',$serviceId]
        ];
        if (!in_array($logType, ['add_all', 'reduce_all'])) {
            if (!empty($logType)) {
                $where[] = ['log_type', '=', $logType];
            }
        } else {
            if ($logType == 'add_all') {
                $where[] = ['status', '=', 1];
            } else {
                $where[] = ['status', '=', 2];
            }
        }

        if (!empty($startAt) && !empty($endAt)) {
            $endAt = $endAt . ' 23:59:59';
            $where[] = ['create_at', 'between', [$startAt, $endAt]];
        } else {
            //$sevenDaysAgo = time() - 7 * 24 * 3600; // 计算7天前的时间戳
            //$sevenDaysAgo = date('Y-m-d H:i:s', $sevenDaysAgo);
            //$where[] = ['create_at', '>=', $sevenDaysAgo];
        }
        $finance = Service::getInstance()->where('id',$serviceId)->find();
        $amount = $finance['serviceAmount'];
        $logList = ServiceAmountLog::getInstance()
            ->where($where)
            ->order('id desc')
            ->page($page, $pageSize)
            ->select();

        $logList = empty($logList) ? [] : $logList->toArray();

        foreach ($logList as &$val) {
            $val['days'] = date('m-d', strtotime($val['createAt']));
        }
        $arr = [];
        foreach ($logList as $v) {
            $arr[$v['days']][] = $v;
        }

        $where = [
            ['service_id','=',$serviceId],
            ['status','=',1]
        ];
        $income = ServiceAmountLog::getInstance()->where($where)->sum('amount');
        $where = [
            ['service_id','=',$serviceId],
            ['status','=',2]
        ];
        $expend = ServiceAmountLog::getInstance()->where($where)->sum('amount');
        $where = [
            ['create_at','>=',date('Y-m-d')],
            ['service_id','=',$serviceId],
            ['status','=',1]
        ];
        $dayAmount = ServiceAmountLog::getInstance()->where($where)->sum('amount');

        return [
            'typeArr' => $this->logTypeData(),
            'rows' => $arr,
            'amount' => $amount, //当前
            'dayAmount' => bcadd($dayAmount, 0, 2), //今日
            'income' => bcadd($income, 0, 2), // 今日收益
            'expend' => bcadd($expend, 0, 2), //支出
            'frozen' => 0, //冻结
        ];
    }

    public function logTypeData(): array
    {
        return [
            [
                'name' => '收入',
                'list' => [
                    ['key' => 'add_all', 'name' => '全部'],
                    ['key' => 'card_add', 'name' => '会员卡核销收入'],
                    ['key' => 'service_add', 'name' => '服务订单收入'],
                ],
            ],
            [
                'name' => '支出',
                'list' => [
                    ['key' => 'reduce_all', 'name' => '全部'],
                ],
            ],
        ];
    }



}
